package com.sto.stoapp.activity.sales;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.manager.SalesSignNameManager;
import com.sto.stoapp.entity.SelectSignNameEntity;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoHomeActivity;

public class SalesAddSignNameActivity extends StoHomeActivity{
	public static final String SIGN_NAME = "sign_name";

	private StoHhmEditText signerEdit, codeEdit;

	private Button addBtn;
	
	private SelectSignNameEntity dataIntent = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_add_sign_name);
		this.setTitleBottom(R.string.sales_sign_add_name,
				HomeBroadAction.SALES_MAN_BROAD);
		initWidget();
		initListener();
	}

	private void initWidget() {
		dataIntent = getIntent().getParcelableExtra(SIGN_NAME);
		signerEdit = (StoHhmEditText) findViewById(R.id.signer);
		codeEdit = (StoHhmEditText) findViewById(R.id.code);
		signerEdit.setInputType(InputType.TYPE_CLASS_TEXT);
		codeEdit.setInputType(InputType.TYPE_CLASS_TEXT);
		addBtn = (Button) findViewById(R.id.add_sign_name);
		if (dataIntent != null) {
			signerEdit.setText(dataIntent.getName());
			codeEdit.setText(dataIntent.getCode());
			addBtn.setText(R.string.sales_sign_name_add);
		}
	}
	
	private void initListener() {
		addBtn.setOnClickListener(new StoOnClickListener(this) {
			
			@Override
			public void mHonClick(View view) {
				// TODO Auto-generated method stub
				saveData();
			}
		});
		
		signerEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				InputMethodManager imm = (InputMethodManager) signerEdit
                        .getContext().getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                if (hasFocus) {
//                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                } else {
                    imm.hideSoftInputFromWindow(signerEdit.getWindowToken(), 0);
                }

			}
		});
		
		signerEdit.setEditDelete(new EditClickListener() {
            
            @Override
            public void onEditDelete() {
                onBackPressed();
            }
            
            @Override
            public void onEditClickListener(View v) {
//                codeEdit.requestFocus();
            }
        });
		codeEdit.setEditDelete(new EditClickListener() {
            
            @Override
            public void onEditDelete() {
                signerEdit.requestFocus();
            }
            
            @Override
            public void onEditClickListener(View v) {
//                addBtn.requestFocus();
            }
        });
	}
	
	private void exitShuRuFa(){
    	InputMethodManager imm = (InputMethodManager) signerEdit
                .getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    	imm.hideSoftInputFromWindow(signerEdit.getWindowToken(), 0);
    }
	
	protected void saveData() {
		if(checkItem()){
			if (TextUtils.isEmpty(signerEdit.getText())
					|| TextUtils.isEmpty(codeEdit.getText())) {
				Helper.showToast(this, getString(R.string.add_input_null));
			} else {
				SelectSignNameEntity entity = new SelectSignNameEntity();
				entity.setCode(codeEdit.getText().toString());
				entity.setName(signerEdit.getText().toString());
				entity.setUpdateType(entity.USER_ADD);
				new UpdateThread(this, dataIntent, entity).start();
			}
		}
	}
	
	private int Chineselength(String value) {
    	int valueLength = 0;
    	String chinese = "[\u0391-\uFFE5]";
    	/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
    	for (int i = 0; i < value.length(); i++) {
    		/* 获取一个字符 */
    		String temp = value.substring(i, i + 1);
    		/* 判断是否为中文字符 */
    		if (temp.matches(chinese)) {
    			/* 中文字符长度为2 */
    			valueLength += 2;
    		} else {
    			/* 其他字符长度为1 */
    			valueLength += 1;
    		}
    	}
    	return valueLength;
    }
	
	private boolean checkItem(){
		boolean ret = true;
		
		if(!isChineseChar(signerEdit.getText().toString())){
			Helper.showSoundToast(this,
					"签名只能数字或字母或中文组成!", false);
			signerEdit.requestFocus();
			return false;
		}
		if(Chineselength(signerEdit.getText().toString()) > 14){
			Helper.showSoundToast(this,
					"签名长度过长,请减少长度!", false);
			signerEdit.requestFocus();
			return false;
		}
		if(!isCharNumber(codeEdit.getText().toString())){
			Helper.showSoundToast(this,
					"代码只能字母或数字组成!", false);
			signerEdit.requestFocus();
			return false;
		}
		
		return ret;
	}
	
	/**
	 * 非法符号判断(只能字母,数字,中文)
	 * 
	 * @param content
	 * @return
	 */
	private boolean isChineseChar(String content) {
		Pattern p = Pattern
				.compile("^[\\w\\u4e00-\\u9fa5]+$");
		Matcher m = p.matcher(content);
		return m.matches();
	}
	
	/**
	 * 只能输入数字和字母
	 * @param content
	 * @return
	 */
	private boolean isCharNumber(String content){
		Pattern p = Pattern
				.compile("^[A-Za-z0-9]+$");
		Matcher m = p.matcher(content);
		return m.matches(); 
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
	//	exitShuRuFa();
		super.onBackPressed();
	}
	
	protected void onDestroy() {
		
		
		super.onDestroy();
	};
	
	class UpdateThread extends BaseThread {

		private SelectSignNameEntity oldEntity, newEntity;

		private Context context;

		public UpdateThread(Context context, SelectSignNameEntity oldEntity,
				SelectSignNameEntity newEntity) {
			super(context);
			this.context = context;
			this.oldEntity = oldEntity;
			this.newEntity = newEntity;
			showDialog();
		}

		@Override
		public void run() {
			super.run();
			if (SalesSignNameManager.getInstance(context).querySingle(newEntity)) {
				// TODO
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						cancelDialog();
						Helper.showToast(context,
								context.getString(R.string.data_exist));
					}
				});
			} else {
				if (oldEntity != null) {
					SalesSignNameManager.getInstance(context).delete(oldEntity);
				}
				if (SalesSignNameManager.getInstance(context).insert(newEntity)) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Helper.showToast(context, getString(R.string.save_success));
							Intent intent = new Intent();
							intent.putExtra(SIGN_NAME, newEntity);
							setResult(Activity.RESULT_OK, intent);
							finish();
						}
					});
				} else {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							Helper.showToast(context, getString(R.string.save_failure));
						}
					});
				}
				cancelDialog();
			}
		}
	}
	
}
